import axios from 'axios';
import qs from 'qs';
import { message } from 'antd';
import Cookies from 'js-cookie';

import { store } from '@/store';
import { setLoginOpen, setUserInfo } from '@/reducers/main';
import { LOGIN, VALIDATE } from '@/config/url';

const abortController = new AbortController();
const { signal } = abortController;
const BASEDIR = import.meta.env.VITE_BASEDIR;


/*
    错误提示，不在这里添加，原因就是很多时候都是好多请求并发请求的，如果在这里提示，那么就会出现一种情况，一下出现很多错误提示
*/
export default function request(url, options = {}) {
    let isUrlEncoded = options.contentType === 'application/x-www-form-urlencoded',
        isFormData = options.contentType === 'multipart/form-data',
        requestUrl = url,
        responseBlob = options.responseType === 'blob',
        Authorization = { token: Cookies.get('aws_phase_token') },
        language = localStorage.getItem('aws_phase_language') || 'en-US',
        progressObj = {};

    if ((!options.method || (['GET', 'DELETE'].includes(options.method?.toUpperCase()))) && options.data && Object.keys(options.data).length) {
        requestUrl += `?${qs.stringify(options.data || {})}`;
    }
    if (options.onUploadProgress && 'function' === typeof (options.onUploadProgress)) {
        progressObj['onUploadProgress'] = options.onUploadProgress;
    }

    let ajaxOption = {
        url: requestUrl,
        method: options.method || 'GET', // 默认 get
        baseURL: ``, // baseURL 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL。
        headers: {
            'Content-Type': options.contentType || 'application/json',
            ...Authorization,
            'Accept-Language': language
        },
        data: isUrlEncoded ? qs.stringify(options.data || {}) : (isFormData ? options.data : JSON.stringify(options.data || {})), // 'PUT', 'POST', 和 'PATCH'时body的参数
        timeout: options.timeout || 60000, // 超时时间 60秒
        responseType: options.responseType || 'json', // 表示服务器响应的数据类型
        ...progressObj,
    };
    return new Promise((resolve, reject) => {
        axios(ajaxOption).then(response => {
            if (200 === response?.status) {
                if (responseBlob) {
                    return resolve(response?.data || null);
                } else {
                    if (response?.data?.code === 0 || response?.data?.code === '0') {
                        resolve(response?.data || null);
                    } else if ((response?.data?.code === -3001 || response?.data?.code === -3002) && VALIDATE !== url) {
                        if (window.location.pathname !== `${BASEDIR}/login`) {
                            Cookies.remove('aws_phase_token');
                            // localStorage.removeItem('language');
                            store.dispatch(setUserInfo({}));
                            localStorage.removeItem("aws_phase_userinfo");
                            window.location.href = `${BASEDIR}/login`;
                        }
                        return reject({ code: 401, msg: 'Unauthorized, please login again', data: null });
                    } else {
                        resolve({
                            code: response?.data?.code,
                            message: response?.data?.message || '',
                            data: response?.data || null
                        });
                    }
                }
            } else {
                reject({
                    code: response?.status || 500,
                    data: null,
                    message: 'Network abnormality'
                });
            }
        }).catch(error => {
            if (error?.response?.status === 401) {
                if (window.location.pathname !== `${BASEDIR}/login`) {
                    Cookies.remove('aws_phase_token');
                    // localStorage.removeItem('language');
                    store.dispatch(setUserInfo({}));
                    localStorage.removeItem("aws_phase_userinfo");
                    window.location.href = `${BASEDIR}/login`;
                }
            } else {
                reject({ code: 500, data: null, message: 'Connection exception, please try again later' });
            }
        });
    });
}
